package jee.boot.common.basic;

import com.fasterxml.jackson.annotation.JsonIgnore;
import jee.boot.common.annotation.Transient;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据Entity类
 * 
 * @author zhilei.wang
 *
 * @param <T>
 */
public abstract class TreeEntity<T extends TreeEntity<T>> extends DataEntity<T> {
	private static final long serialVersionUID = 1L;

	/**
	 * 所有父级编号
	 */
	protected String parentIds;
	/**
	 * 名称
	 */
	protected String name;
	/**
	 *  级别
	 */
	protected Integer level;
	/**
	 * 排序
	 */
	protected Integer sort;
	/**
	 * 一级子类
	 */
	@Transient
	protected List<T> children = new ArrayList<>();

	public TreeEntity() {
		super();
	}

	public TreeEntity(String id) {
		super(id);
	}

	/**
	 * 父对象，只能通过子类实现，父类实现mybatis无法读取
	 *
	 * @return
	 */
	public  abstract T getParent();

	/**
	 * 父对象，只能通过子类实现，父类实现mybatis无法读取
	 *
	 * @return
	 */
	public abstract void setParent(T parent);

	public String getParentIds() {
		return parentIds;
	}

	public void setParentIds(String parentIds) {
		this.parentIds = parentIds;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getSort() {
		return sort;
	}

	public void setSort(Integer sort) {
		this.sort = sort;
	}

	public Integer getLevel() {
		return level;
	}

	public void setLevel(Integer level) {
		this.level = level;
	}

//	public String getParentId() {
//		String id = null;
//		if (parent != null) {
//			id = getParent().getId();
//		}
//		return StringUtils.isNotBlank(id) ? id : TreeDefinitionService.TREE_ROOT_ID;
//	}

	public List<T> getChildren() {
		return children;
	}

	public void setChildren(List<T> children) {
		this.children = children;
	}

	/**
	 * 树表结构-找到所有子节点(必须)
	 * @return
	 */
	@JsonIgnore
	public String getFindByParentIdsLikeSql(){
		AttrTable table = attrTable();
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT ");
		sql.append(" a.id, a.parent_id AS \"parent.id\", a.parent_ids ");
		sql.append(" FROM ").append(table.getTableName()).append(" a");
		sql.append(" WHERE a.parent_ids LIKE  #{parentIds}");
		sql.append(" ORDER BY a.sort ASC");
		return sql.toString();
	}
	/**
	 * 树表结构-找到所有子节点(必须)
	 * @return
	 */
	@JsonIgnore
	public String getUpdateParentIdsSql(){
		AttrTable table = attrTable();
		StringBuilder sql = new StringBuilder();
		sql.append("UPDATE ").append(table.getTableName()).append(" SET ");
		sql.append("parent_id = #{parent.id}, parent_ids = #{parentIds}");
		sql.append(" WHERE id = #{id}");
		return sql.toString();
	}
}
